package net.grandnature.android.morse.player;

import java.io.IOException;
import java.util.ArrayList;

import android.content.Context;
import android.os.Vibrator;

public class MorseVibratePlayer implements MorsePlayer {
	
	private Vibrator vibrator;
	private ArrayList<Long> pattern = new ArrayList<Long>();
	private final long LONG_SIGNAL;
	private final long SHORT_SIGNAL;
	private boolean on = false;
	private long currentValue = 0;
	
	public MorseVibratePlayer(int shortTime){
		on = false;
		LONG_SIGNAL = shortTime * 3;
		SHORT_SIGNAL = shortTime * 1;
		
	}

	public void setContext(Context context){
		this.vibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
	}
	
	@Override
	public void longSignal() {
		if(!on) {
			this.pattern.add(currentValue);
			currentValue = 0;
		}
		currentValue+=LONG_SIGNAL;
		on = true;
	}

	@Override
	public void shorSignal() {
		if(!on) {
			this.pattern.add(currentValue);
			currentValue = 0;
		}
		currentValue+=SHORT_SIGNAL;
		on = true;
	}

	@Override
	public void silent(int length) {
		if(on) {
			this.pattern.add(currentValue);
			currentValue = 0;
		}
		currentValue+=length * SHORT_SIGNAL;
		on = false;
	}

	@Override
	public void close() throws IOException {
		this.pattern.add(currentValue);
		long[] longs = new long[pattern.size()];
		int i = 0;
		for( Long v:pattern){
			longs[i] = v;
			i++;
		}
		this.vibrator.vibrate(longs, -1);
		
	}
	

}
